<?php


namespace app\admin\controller;

use app\admin\service\Auth;
use DI\Annotation\Inject;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use support\annotation\NoNeedRight;
use support\Request;
use support\Validator;

/**
 * @NoNeedRight()
 */
class Login extends BaseController
{
    /**
     * @var Auth
     * @Inject()
     */
    protected $service = null;

    public $noNeedLogin = [
        '*'
    ];

    public $excludeLogined = [
        '*'
    ];

    public function index(Request $request) {
        return view('login/index');
    }

    public function captcha(Request $request)
    {
        $phraseBuilder = new PhraseBuilder(4, '0123456789');
        $builder = new CaptchaBuilder(null, $phraseBuilder);
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    public function login(Request $request) {
        $formData = $request->post('form');
        $data = $this->validate($formData, [
            'username' => 'required|min:2|max:12',
            'password' => 'required|min:6|max:64',
            'captcha' => 'required|size:4'
        ],[
            'required' => ':attribute必填',
            'min' => ':attribute最小:min位',
            'max' => ':attribute最大:max位',
            'size' => '请输入:size位:attribute'
        ], [
            'username' => '账户',
            'password' => '密码',
            'captcha' => '验证码'
        ]);
        if($data['captcha'] != $request->session()->get('captcha')) {
            $this->error("验证码不正确!");
        }
        $row = $this->service->login($data['username'], $data['password']);
        $homeUrl = '/admin/index/index';
        $this->success($row->nickname . ", 欢迎您的登录成功!", [
            'url' => $homeUrl
        ]);
    }
}
